package com.epfresh.api.widget;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;

import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.T;
import com.epfresh.supplier.R;
import com.google.gson.Gson;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.util.HashMap;
import java.util.Map;

public class ShareCouponDialog extends Dialog implements View.OnClickListener {
    View iv_flag_1,iv_flag_2,iv_flag_3,iv_flag_4;

  //  private View vCancel;
    private View vContact;
    private View vMessage;
    private View vWechat;
    private View vFriendly;
    private View vCopyUrl;
    private Activity activity;

    public String phone;
    public String couponId;
    public String couponNumber;

    EditText tvPhone;
    public ShareCouponDialog(Activity context) {

        this(context, R.style.ActionSheetDialogStyle);

    }

    public ShareCouponDialog(Activity context, int theme) {
        super(context, theme);
        activity = context;
        builer();
    }

    public ShareCouponDialog builer() {

        View v = LayoutInflater.from(getContext()).inflate(R.layout.layout_coupon_share, null);

        setContentView(v);
        Window dialogWindow = getWindow();
        dialogWindow.setGravity(Gravity.CENTER);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = LocalDisplay.SCREEN_WIDTH_PIXELS;
        dialogWindow.setAttributes(lp);
        tvPhone = (EditText)findViewById(R.id.et_phone);
//        vCancel = findViewById(R.id.v_cancel);
        vContact = findViewById(R.id.rl_contact);
        vMessage = findViewById(R.id.rl_message);
        vWechat = findViewById(R.id.rl_wechat);
        vFriendly = findViewById(R.id.rl_wechat_friendly);
        vCopyUrl = findViewById(R.id.tv_copy_share_url);
      //  vCancel.setOnClickListener(this);
        vContact.setOnClickListener(this);
        vMessage.setOnClickListener(this);
        vWechat.setOnClickListener(this);
        vFriendly.setOnClickListener(this);
//        vCopyUrl.setOnClickListener(this);
        View cancel = findViewById(R.id.v_cancel);
        cancel.setOnClickListener(this);
        View sure = findViewById(R.id.v_sure);
        sure.setOnClickListener(this);

        iv_flag_1 = findViewById(R.id.iv_flag_1);
        iv_flag_2 = findViewById(R.id.iv_flag_2);
        iv_flag_3 = findViewById(R.id.iv_flag_3);
        iv_flag_4 = findViewById(R.id.iv_flag_4);

        return this;
    }

    @Override
    public void show() {


    }

    public void showDialog() {
        super.show();
    }

    @Override
    public void onClick(View v) {
/*        if(v.getId() == R.id.rl_message) {
            EditText tvPhone = (EditText)findViewById(R.id.tv_phone);
            if (InputControl.isEmpty(tvPhone)) {
                T.toast("请输入手机号");
                return;
            }
            if (!InputControl.isPhoneNumber(tvPhone)) {
                T.toast("请输入正确的手机号");
                return;
            }
                phone = tvPhone.getText().toString();
                shareMessage();
        }
        dismiss();
        share(v.getId());*/
        switch (v.getId()) {
            case R.id.v_sure:
                sure();
                break;
            case R.id.v_cancel:
                dismiss();
                break;
            case R.id.rl_wechat:
                tvPhone.setVisibility(View.INVISIBLE);
                hideFlag();
                iv_flag_1.setVisibility(View.VISIBLE);
                flag = R.id.rl_wechat;
                break;
            case R.id.rl_wechat_friendly:
                hideFlag();
                tvPhone.setVisibility(View.INVISIBLE);
                iv_flag_2.setVisibility(View.VISIBLE);
                flag = R.id.rl_wechat_friendly;
                break;
            case R.id.rl_message:
                tvPhone.setVisibility(View.VISIBLE);
                phone = tvPhone.getText().toString();
                hideFlag();
                iv_flag_3.setVisibility(View.VISIBLE);
                flag = R.id.rl_message;
                break;
            case R.id.rl_contact:
                tvPhone.setVisibility(View.VISIBLE);
                hideFlag();
                iv_flag_4.setVisibility(View.VISIBLE);
                flag = R.id.rl_contact;
                initCall();

                break;
        }
    }
    int flag = 0; //1,weixin;2,3,4

    void sure(){
        if(flag==0){
            T.toast("请选择赠送方式");
            return;
        }
        if(flag==R.id.rl_wechat){
            share(R.id.rl_wechat);
            return;
        }
        if(flag==R.id.rl_wechat_friendly){
            share(R.id.rl_wechat_friendly);
            return;
        }
        else {
            shareMessage();
            return;
        }
    }

    void hideFlag(){
        iv_flag_1.setVisibility(View.GONE);
        iv_flag_2.setVisibility(View.GONE);
        iv_flag_3.setVisibility(View.GONE);
        iv_flag_4.setVisibility(View.GONE);
    }


    private String pageUrl;
    private String imageUrl;
    private String text;
    private String title;
    private String id;

    public void setShareContent(String url, String imageUrl, String text, String title, String id) {
        this.pageUrl = url;
        this.imageUrl = imageUrl;
        this.text = text;
        this.title = title;
        this.id = id;
    }

    public void showDialog(String url, String imageUrl, String text, String title, String id) {
        this.setShareContent(url, imageUrl, text, title, id);
        super.show();
    }

    public void showDialog(String url, String imageUrl, String text, String title) {
        this.setShareContent(url, imageUrl, text, title, null);
        super.show();
    }
//供货端 //1105418748 0JAlakouvQUNS5Iy
    private void share(int type) {
        UMImage image = null;
        if (imageUrl != null && !"".equals(imageUrl)) {
            image = new UMImage(activity, imageUrl);
        }
        String url = this.pageUrl;
        String text = this.text;
        String title = this.title;
        final UMWeb web = new UMWeb(url); //切记切记 这里分享的链接必须是http开头
        web.setTitle(title);//标题
        web.setThumb(image);  //缩略图
        web.setDescription(text);//描述
        switch (type) {
            case R.id.rl_qq:
                new ShareAction(activity).setPlatform(SHARE_MEDIA.QQ)
                        .withMedia(web)
                        .setCallback(umShareListener)
                        .share();
                break;
            case R.id.rl_qqzone:
                new ShareAction(activity).setPlatform(SHARE_MEDIA.QZONE)
                        .withMedia(web)
                        .setCallback(umShareListener)
                        .share();
                break;
            case R.id.rl_wechat:
                new ShareAction(activity).setPlatform(SHARE_MEDIA.WEIXIN)
                        .withMedia(web)
                        .setCallback(umShareListener)
                        .share();

                break;
            case R.id.rl_wechat_friendly:
                new ShareAction(activity).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                        .withMedia(web)
                        .setCallback(umShareListener)
                        .share();
                break;
            default:
                break;
        }

    }
    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {

            if (activity != null)
                T.toast(BaseApplication.getDoc().getShared());
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            if (activity != null)
                T.toast("分享失败");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
//            if (activity != null)
//                Toast.makeText(getContext().getApplicationContext(), " 分享取消", Toast.LENGTH_SHORT).show();
        }
    };


    public void onResult(int requestCode, int resultCode, Intent data) {
        if (activity != null)
            UMShareAPI.get(activity).onActivityResult(requestCode, resultCode, data);
    }


    private void shareMessage() {
        RequestEntitySupply<Map<String, String>> entity = new RequestEntitySupply<>();
        Map<String, String> map = new HashMap<>();
        phone = tvPhone.getText().toString();
        if(phone==null||phone.equals("")){
            T.toast("手机号码不可为空，请手动输入或从通讯录选取");
            return;
        }
        map.put("phone",phone);
        map.put("supplierCouponId", couponId);
        entity.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_coupon_coupon_forwardByMsg);
        entity.setParameters(map);
        ((BaseActivity)activity).request(entity, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_coupon_coupon_forwardByMsg, new OnRequestListener<StatusEntity>() {
            @Override
            public StatusEntity jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, StatusEntity.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                ((BaseActivity)activity).hideProgressDialog();
                T.toast("服务器出现小问题，请稍后再试");
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                ((BaseActivity)activity).hideProgressDialog();
                T.toast("服务器出现小问题，请稍后再试");
            }

            @Override
            public void onStart(Object tag) {
                ((BaseActivity)activity).showProgressDialog();
            }

            @Override
            public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
                ((BaseActivity)activity).hideProgressDialog();
                StatusEntity responseElement = response.getResponseElement();
                if (responseElement.isSuccess()) {
                 //   ((MyCouponActivity)activity).requestOrderList(0);
                    T.toast("发送成功");
                    dismiss();
                }else {
                    T.toast("请稍后再试");
                }
            }
        });
    }


    public void setPhone(String phone){
        if(phone==null)
            return;
        tvPhone.setText(phone);
        tvPhone.setSelection(tvPhone.getText().length());
        this.phone = tvPhone.getText().toString();
    }

    public void initCall()
    {
        if (ContextCompat.checkSelfPermission(activity,
                Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED)
        {

            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.READ_CONTACTS},
                    0x1);
        } else
        {
            callPhone();
        }
    }

    public void callPhone()
    {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setData(ContactsContract.Contacts.CONTENT_URI);
        activity.startActivityForResult(intent, 0x1);
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
    {

        if (requestCode == 0x1)
        {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                callPhone();
            } else
            {
                T.toast("Permission Denied");
            }
            return;
        }
    }

}
